import os
import random
import chardet
import uuid

uuid = uuid.uuid1()
dir_path = '/Users/Sheldon/Downloads/IOS'  # 目标目录路径
new_lines = []  # 保存处理后的内容

print("{}-查找开始".format(uuid))
# 遍历所有文件，读取它们的内容到read_lines列表
for file_name in os.listdir(dir_path):
    file_path = os.path.join(dir_path, file_name)
    if os.path.isfile(file_path):
        # 使用 chardet 库自动检测文件编码方式
        with open(file_path, "rb") as f:
            content = f.read()
            result = chardet.detect(content)
            encoding = result["encoding"]
        with open(file_path, 'r', encoding=encoding) as file:
            lines = file.readlines()
            for line in lines:
                # 遍历所有文件的内容，去除关键字后存入new_lines列表 if '<nil>' not in line and 'file_size' in line:
                if '<nil>' not in line:
                    new_lines.append(line)
        # os.remove(file_path)  # 删除原文件

# 将new_lines中的内容写入同一个文件
new_file_name = str(random.randint(0, 1000000)) + '.txt'
new_file_path = os.path.join(dir_path, new_file_name)
with open(new_file_path, 'w', encoding=encoding) as new_file:
    new_file.writelines(new_lines)
print("{}-操作结束".format(uuid))
